import os
from shutil import copyfile
import Compare as cp
import Standard as sd
import CToXML as ct
import pymysql
import numpy as np
import pandas as pd
import data_process as dp


database_name = "jizu202501"
def p_c(dir_temp,homework_id,dir_second):
    list = []
    com = cp.Compare()
    sta = sd.Standard()
    cto = ct.CToXML()
    log_path = "blueprints/xml/test/log.txt"
    xml_path = "blueprints/xml/test/xml"
    
    # print("please input directory name")
    dir = dir_temp +'/'+ dir_second
    if not os.path.exists(log_path):
        os.makedirs(os.path.dirname(log_path))
    
    # 创建 MySQL 连接
    db = pymysql.connect(
        host="localhost",
        user="root",
        password='A310a310',
        database=database_name
    )
    # 创建游标
    cursor = db.cursor()
    
    with open(log_path, "w") as sw:
        dic_info = os.listdir(dir)
        for file_name in dic_info:
            file_path = os.path.join(dir, file_name)
            print(file_name)
            temp1 = sta.get_stand(file_path, "blueprints/xml/temp/")
            temp2 = os.path.join(xml_path, file_name + ".xml")
            cto.c_to_xml(temp2, "blueprints/xml/temp/j.txt")
    
    dic = os.listdir(xml_path)
    for file_name in dic:
        list.append(os.path.join(xml_path, file_name))
    

    with open(log_path, "a") as sw:
        for i in range(len(list)):
            for j in range(i + 1, len(list)):
                
                n1 = com.compare_main(list[i], list[j])
                n2 = com.compare_main(list[j], list[i])
                n = (n1 + n2) / 2
                semblance_percentage = round(n * 100, 2)
                
                student_id1 = list[i].split("/")[-1].split(".")[0]
                student_id2 = list[j].split("/")[-1].split(".")[0]
                combined_student_ids = f"{student_id1} {student_id2}"
                
                # 检查是否存在相同 hid 和 sid 的数据
                check_query = "SELECT * FROM copy WHERE hid = %s AND sid = %s"
                check_data = (homework_id, combined_student_ids)
                cursor.execute(check_query, check_data)
                existing_data = cursor.fetchone()
                
                if semblance_percentage < 70 and existing_data:
                    # 删除数据库表 copy 中的数据
                    delete_query = "DELETE FROM copy WHERE hid = %s AND sid = %s"
                    delete_data = (homework_id, combined_student_ids)
                    cursor.execute(delete_query, delete_data)
                    db.commit()  # 提交更改
                    
                elif semblance_percentage > 70 and existing_data :
                    # 更新相似度数据
                    update_query = "UPDATE copy SET semblance = %s WHERE hid = %s AND sid = %s"
                    update_data = (semblance_percentage, homework_id, combined_student_ids)
                    cursor.execute(update_query, update_data)
                    db.commit()  # 提交更改
                elif semblance_percentage > 70:
                    # 插入数据到数据库表 copy
                    insert_query = "INSERT INTO copy (hid, sid, semblance) VALUES (%s, %s, %s)"
                    insert_data = (homework_id, combined_student_ids, semblance_percentage)
                    cursor.execute(insert_query, insert_data)
                    db.commit()  # 提交更改

                    temp = f"{list[i]} and {list[j]} {semblance_percentage}%"
                    sw.write(temp + "\n")
                    print(temp)
     # 关闭游标和数据库连接
    cursor.close()
    db.close()
    print("success")
    delete_folder_contents("blueprints/xml/test/xml")
    csv_out(dir_temp,homework_id)

def plagiaris_check(dir_temp,homework_id):
    # 读取dir_temp目录下的文件夹名字,存入list
    list = []
    for folder in os.listdir(dir_temp):
        if os.path.isdir(os.path.join(dir_temp, folder)):
            list.append(folder)
    for i in range(len(list)):
        dir_second = list[i]
        p_c(dir_temp,homework_id,dir_second)
    dp.data_process(dir_temp,homework_id)
        
# # 统计教学班抄袭人数情况   
# def count(dir_temp):
#     # 读取copy.txt文件，数其行数
#     with open(os.path.join(dir_temp, 'copy.txt'), "r") as copy_file:
#         lines = copy_file.readlines()
#         count = len(lines)
#         # 统计抄袭人数
    
def delete_folder_contents(folder_path):
    # 确保路径存在
    if os.path.exists(folder_path):
        # 遍历文件夹中的所有文件和子文件夹
        for item in os.listdir(folder_path):
            item_path = os.path.join(folder_path, item)
            if os.path.isfile(item_path):
                # 如果是文件，直接删除
                os.remove(item_path)
            elif os.path.isdir(item_path):
                # 如果是子文件夹，递归删除其内容
                delete_folder_contents(item_path)
                # 删除空的子文件夹
                os.rmdir(item_path)

import pymysql


def csv_out(dir_temp, hid):
    # 数据库连接配置
    db_config = {
        "host": "localhost",
        "user": "root",
        "password": "A310a310",
        "database": database_name
    }

    # 设置log.txt文件路径
    log_path = f"{dir_temp}/log.txt"

    # 连接数据库
    with pymysql.connect(**db_config) as db:
        # 创建游标
        with db.cursor() as cursor:
            # 从数据库表 copy 中获取数据并写入log.txt文件
            query = "SELECT sid FROM copy WHERE hid = %s"
            cursor.execute(query, hid)
            
            # 将获取的数据写入log.txt文件
            with open(log_path, "w") as log_file:
                for row in cursor.fetchall():
                    log_file.write(str(row[0]) + "\n")
        # 读取log.txt文件中的数据并转换为数组
    with open(log_path, "r") as log_file:
        lines = log_file.readlines()
        data = [list(map(int, line.strip().split())) for line in lines]

    # 转换为NumPy数组
    data_array = np.array(data)
    print(data_array)
            

    # 创建一个空列表来存储分组后的数据
    clusters = []

    # 遍历数据并按照每行数据内部的数值进行分组，去除重复值
    for point in data_array:
        point_set = set(point)
        found = False
        for cluster in clusters:
            if not cluster.isdisjoint(point_set):
                cluster.update(point_set)
                found = True
                break
        if not found:
            clusters.append(point_set)

    # 进行合并具有重复数字的簇的迭代操作
    merged_clusters = []
    while clusters:
        current_cluster = clusters.pop()
        merged = False
        for cluster in clusters: 
            if not cluster.isdisjoint(current_cluster):
                cluster.update(current_cluster)
                merged = True
                break
        if not merged:
            merged_clusters.append(current_cluster)

    # 将集合转换回列表形式
    result_clusters = [list(cluster) for cluster in merged_clusters]
    
    
    
    # 将 result_clusters 转换为 DataFrame
    df = pd.DataFrame(result_clusters)

    # 转置 DataFrame 以使每个版本在单独的列中
    df = df.T

    # 从df中按照学生所在班级提取出df1,df3
    # 创建两个空的DataFrame用于存储不同班级的数据
    df1 = pd.DataFrame()
    db = pymysql.connect(
        host="localhost",
        user="root",
        password='A310a310',
        database=database_name
    )
    # 创建游标
    cursor = db.cursor()
    
    
    # 查询student表中的class_id2列,结果去重后保存到class_id2_list中
    query = "SELECT DISTINCT class_id2 FROM student"
    cursor.execute(query)
    class_id2_list = cursor.fetchall()
    
    
    
    # 处理每一个班级的数据
    for Class in class_id2_list:
        # 遍历DataFrame的列
        for column_name in df.columns:
            # 获取第一个元素并转换为整数
            element = int(df[column_name][0])
            # 查询学生所在班级（student表中的ID列是BIGINT）
            query = "SELECT class_id2 FROM student WHERE ID = %s"
            cursor.execute(query, (element,))
            class_id2 = cursor.fetchone()
            if class_id2:
                if class_id2[0] == Class[0]:
                    df1[column_name] = df[column_name]
                    
                    
        df1.columns = [f"抄袭版本{i + 1}" for i in range(len(df1.columns))]
        file_name = f"{dir_temp}/copy{Class[0]}.xlsx"
        df1.to_excel(file_name, index=False)
        # 清空df1
        df1 = pd.DataFrame()
    
    
    # 重命名列以匹配所需的格式
    df.columns = [f"抄袭版本{i + 1}" for i in range(len(df.columns))]


    # 保存 DataFrame 到 Excel 文件
    excel_file_path = f"{dir_temp}/copy.xlsx"
    df.to_excel(excel_file_path, index=False)
    # 打印结果
    for i, cluster in enumerate(result_clusters):
        print(f"抄袭版本{i + 1}:", cluster)
    # 将结果写入copy.txt文件
    with open(f"{dir_temp}/copy.txt", "w") as copy_file:
        for i, cluster in enumerate(result_clusters):
            copy_file.write(f"抄袭版本{i + 1}: {cluster}\n")
    
    
    
    # with open(f"{dir_temp}/copy.txt", "w") as copy_file:
    #     for i, cluster in enumerate(result_clusters):
    #         copy_file.write(f"Plagiarism_version{i + 1}: {cluster}\n")
            


    



if __name__ == "__main__":
    dir_temp = "homework_uploads/3-输入一行字符，分别统计出其中英文字母、空格、数字和其它字符的个数"
    hid = 3
    plagiaris_check(dir_temp,hid)
